<template>
  <view style="width: 100%; min-height: 100vh;">
    <view style="width: 100%; padding:  128upx 80upx 0 80upx;">
      <view class="flex flex-direction align-center" style="margin-bottom: 108upx;">
        <image src="/static/icon/1024.png"
               style="width: 120upx; height: 120upx; border-radius: 50%; margin-bottom: 20upx;"></image>
        <view style="font-size: 40upx; font-weight: bold;">注册</view>
      </view>
      <view style="margin-bottom: 98upx;">
        <view class="flex align-end"
              style="width: 100%; height: 118upx; padding-bottom: 20upx; border-bottom: 2upx solid #F5F5F5;">
          <input type="number" v-model="phonenum" placeholder="请输入手机号" maxlength="11"
                 placeholder-style="color: #DCDCDC;" style=" font-size: 28upx; width: 100%;">
        </view>
        <view class="flex justify-between  align-end"
              style="width: 100%; height: 118upx; padding-bottom: 20upx; border-bottom: 2upx solid #F5F5F5;">
          <input type="number" v-model="captcha_code" placeholder="请输入验证码" placeholder-style="color: #DCDCDC;"
                 style=" font-size: 28upx; width: 60%;">
          <view v-show="!is_obtain" @click="handleGetVerification" style="font-size: 28upx; color: #008BCC;">获取验证码
          </view>
          <view v-show="is_obtain && count" style="font-size: 28upx; color: #999999;">
            <span @click="handleReGetTime">
              <span>{{ count }}</span>
              <span>s后重试</span>
            </span>
          </view>
        </view>
        <view class="flex align-end"
              style="width: 100%; height: 118upx; padding-bottom: 20upx; border-bottom: 2upx solid #F5F5F5;">
          <input type="password" v-model="password" placeholder="请输入注册密码" placeholder-style="color: #DCDCDC;"
                 style="font-size: 28upx; width: 100%;">
        </view>
        <view v-if="test_password" style="font-size: 20upx; color: #E52718;">密码由数字和字母组成且不小于6位数</view>
      </view>
      <view class="flex flex-direction align-center">
        <view class="flex align-center" style="margin-bottom: 16upx;">
          <view class="flex align-center justify-center" @click="radio = !radio">
            <image :src="radio ? selected_img : no_selected_img" alt="" style="width: 24upx; height: 24upx;"></image>
          </view>
          <view style="margin-left: 8upx; font-size: 24upx;">
            已阅读并同意 <span style="color: #E52718;" @click="handleToAgreement(1)">《艺帮用户协议》</span>和 <span
              style="color: #E52718;" @click="handleToAgreement(0)">《隐私政策》</span>
          </view>
        </view>
        <view @click=" handleToRegistration()" class="flex align-center justify-center"
              :style="`background-color: ${radio?'#E52718':' #D8D8D8'}`"
              style="width: 596upx; height: 80upx; margin-bottom: 30upx; color: white; font-size: 28upx; border-radius: 40upx;">
          立即注册
        </view>
        <view @click="handleToLogin" style="font-size: 28upx; color: #666666; margin-bottom: 36upx;">已有账号</view>
        <view @click="handleToGuestLogin" style="font-size: 28upx; color: #666666;">游客登录</view>
      </view>
    </view>
  </view>
</template>
<script>
import {accountUser_register, vertify_sendVertifyCode} from "api/login/login"
import { setJYJPush, getRegistrationID } from "utils/jyJpush";
export default {
  data() {
    return {
      phonenum: '', //手机号
      captcha_code: '', //验证码
      is_obtain: false, //是否获取验证码
      count: 60, //倒计时
      timer: '', //定时器
      time: '', //定时器
      password: '', //密码
      radio: false, //选择协议
      test_password: false, //校验密码
      is_agree: false,
      selected_img: '/static/icon/xuanzhong@2x.png', //选中图片
      no_selected_img: '/static/icon/weixuanzhong@2x.png', //未选中图片
      registration_id: '',//设备号
      globalData: {
        is_tourist: 1
      }
    }
  },
  methods: {
    //选择协议

    handleChangeAgreement() {
      this.radio = !this.radio;
    },
    //获取验证码
    handleGetVerification() {
      if (!this.phonenum) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return;
      }
      this.is_obtain = true;
      this.count = 60;
      this.countDown()
      vertify_sendVertifyCode({phonenum: this.phonenum, type: 'check'}).then(res => {
        uni.showToast({
          title: '发送成功!',
          icon: 'none'
        })
      }).catch(err => {
        this.is_obtain = false;
        clearInterval(this.timer);
        clearTimeout(this.time);
        uni.showToast({
          title: err.msg,
          icon: 'none'
        })
      })
    },
    //游客登录
    handleToGuestLogin(){
      getApp().globalData.is_tourist = 1;
      uni.switchTab({
        url: '/pages/index/index?is_tourist=1'
      });
    },
    //定时器
    countDown() {
      this.time = setTimeout(() => {
        if (this.count > 0) {
          this.count--;
          this.countDown()
        } else {
          this.is_obtain = false;
          clearInterval(this.timer);
          clearTimeout(this.time);
        }
      }, 1000)
    },
    //重新计时
    handleReGetTime() {
      if (!this.count) {
        this.count = 60;
        this.handleGetVerification();
      }
    },
    //去协议页
    handleToAgreement(type) {
      this.$uniNavigateTo({
        url: '/pages/login/agreement',
        query: {
          type
        }
      })
    },
    //注册
    handleToRegistration() {
      if (!this.radio) {
        return;
      }
      const validateToast = (vm, rules) => {
        return new Promise((resolve, reject) => {
          Object.keys(rules).forEach((key) => {
            const segments = key.split('.')
            const item = rules[key]
            item.forEach((ruleItem) => {
              const value = segments.reduce((total, item) => total && total[item], vm)
              // 必填
              if (ruleItem.required && !value) {
                reject(ruleItem.message)
              }
              // 正则
              if (ruleItem.pattern && !ruleItem.pattern.test(value)) {
                reject(ruleItem.message)
              }
            })
          })
          resolve(true)
        })
      }
      const validate_val_obj = {
        phonenum: this.phonenum,
        captcha_code: this.captcha_code,
        password: this.password,
        radio: this.radio,
        registration_id: this.registration_id,
      }
      const rules = {
        phonenum: [
          {required: true, message: '请输入手机号'},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号格式错误'} // 正则校验
        ],
        // captcha_code: [
        //   {required: true, message: '请输入验证码'}
        // ],
        password: [
          {required: true, message: '请输入密码'},
          {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]/} // 正则校验
        ],
        radio: [
          {required: true, message: '请阅读并同意《艺帮用户协议》和《隐私政策》'}
        ],
      }
      this.test_password = !(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/.test(this.password));
      if (this.test_password) {
        return;
      }
      validateToast(validate_val_obj, rules).then(valid => {
        accountUser_register(validate_val_obj).then(res => {
          console.log(res)
          let get_user_info = {
            nick_name: res.data.nick_name,
            avatar: res.data.avatar,
            token: res.data.token,
            phonenum: res.data.phonenum,
            id: res.data.id
          }
          uni.setStorageSync('user_info', get_user_info)
          uni.switchTab({
            url: '/pages/index/index'
          })
        }).catch(err => {
          console.log(err)
          uni.showToast({
            title: err.msg,
            icon: 'none'
          })
        })
      }).catch(err => {
        if (err) {
          uni.showToast({
            icon: 'none',
            title: err,
          })
        }
      })
    },
    handleToLogin() {
      this.phonenum = '';
      this.captcha_code = '';
      this.password = '';
      this.$uniNavigateTo({
        url: '/pages/login/login'
      })
    }

  },
  async onLoad(){
    //极光推送
    await setJYJPush();
    this.registration_id = await getRegistrationID();
  },
  beforeDestroy() {
    console.log('禁止定时器')
    clearInterval(this.timer);
    clearTimeout(this.time);
  }
}
</script>
<style lang="less" scoped>
/deep/ uni-radio .uni-radio-input {
  width: 24upx;
  height: 24upx;
  border: 1px solid #000000;
  background-color: #ffffff !important;
}

/deep/ uni-radio:not([disabled]) .uni-radio-input:hover {
  background-color: #000000;
  border-color: #000000 !important;
}

/deep/ uni-radio .uni-radio-input::after {
  background-color: #000000 !important;
  border: 1px solid #ffffff !important;
  left: -1 !important;
}
</style>
